<?php

namespace Regard\NewsBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Regard\NewsBundle\Form\NewsType;
use Regard\NewsBundle\Entity\News;
use Symfony\Component\HttpFoundation\RedirectResponse;
use JMS\SecurityExtraBundle\Annotation\Secure;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class NewsController extends Controller
{
    public function __construct() {
        ;
    }
    
    public function indexAction($name)
    {
        return $this->render('RegardNewsBundle:Default:index.html.twig', array('name' => $name));
    }
    
    /**
     * Show the news list
     * @return type render
     */
    public function listNewsAction($all = null)
    {
        $view = 'RegardNewsBundle:News:listNews.html.twig';
        
        $repoNews = $this->getDoctrine()
                        ->getManager()
                        ->getRepository('RegardNewsBundle:News');
		
		if (true === $this->get('security.context')->isGranted('ROLE_ADMIN')) {
			$newsList = $repoNews->findBy(array(), array('date' => 'desc'), 50);
		} else {
			if ($all == "all") {
				$newsList = $repoNews->findBy(array('isToPublish' => true), array('date' => 'desc'), 10);
			} else {
				$newsList = $repoNews->findBy(array('isToPublish' => true), array('date' => 'desc'), 5);
			}
		}
        
        
        $parameters = array(
            'newsList' => $newsList
        );
        
        return $this->render($view, $parameters);
    }
    
    /**
     * Show the selected news
     * @param int $newsId
     * @param String $newsTitle
     * @return type
     * @throws type
     */
    public function showNewsAction($newsId, $newsTitle)
    {
        $view = 'RegardNewsBundle:News:showNews.html.twig';
        
        $repoNews = $this->getDoctrine()
                        ->getManager()
                        ->getRepository('RegardNewsBundle:News');
        
        $news = $repoNews->find($newsId);
        
        // if no news has this id
        if($news === null)
        {
          throw $this->createNotFoundException('News[id='.$newsId.'] does not exist.');
        }
        
        $parameters = array(
            'news' => $news
        );
        
        return $this->render($view, $parameters);
    }
    
    /**
     * @Secure(roles="ROLE_ADMIN")
     * @return render view
     */
    public function addNewsAction() 
    {
        $view = 'RegardNewsBundle:News:addEditNews.html.twig';
		
		$request = $this->get('request');
		$news = new News();
		
		$form = $this->createForm(new NewsType, $news);
		
		if ('POST' == $request->getMethod()) {
			$form->bind($request);
			
			if ($form->isValid()) {
				$em = $this->getDoctrine()->getManager();
				$em->persist($news);
                $em->flush();
				
				$this->get('session')->getFlashBag()->add('notice', 'Actualité ajoutée');
				
                // redirect to avoid resubmission
                return new RedirectResponse($this->generateUrl('regard_news_list'));
			} else {
				$this->get('session')->getFlashBag()->add('notice', 'Erreur : Formulaire invalide');
			}
		}
        
        return $this->render($view, array('form' => $form->createView(),
                                        'news' => $news));
    }
    
    /**
     * @Secure(roles="ROLE_ADMIN")
	 * @param String $newsId
     * @return render view
     */
    public function editNewsAction($newsId) 
    {
        $view = 'RegardNewsBundle:News:addEditNews.html.twig';
		
		$request = $this->get('request');
		
		if (!$news = $this->getDoctrine()->getManager()->getRepository('RegardNewsBundle:News')->find($newsId)) {
			throw new NotFoundHttpException('Cette news n\'existe pas');
		}
		
		$form = $this->createForm(new NewsType, $news);
		
		if ('POST' == $request->getMethod()) {
			$form->bind($request);
			
			if ($form->isValid()) {
				$em = $this->getDoctrine()->getManager();
				$em->persist($news);
                $em->flush();
				
				$this->get('session')->getFlashBag()->add('notice', 'Actualité modifiée');
				
                // redirect to avoid resubmission
                return new RedirectResponse($this->generateUrl('regard_news_list'));
			}
		}
        
        return $this->render($view, array('form' => $form->createView(),
                                        'news' => $news));
    }
    
    /**
     * @Secure(roles="ROLE_ADMIN")
	 * @param String $newsId
     * @return render view
     */
    public function removeNewsAction($newsId) 
    {
		if (!$news = $this->getDoctrine()->getManager()->getRepository('RegardNewsBundle:News')->find($newsId)) {
			throw new NotFoundHttpException('Cette news n\'existe pas');
		}
		
		$em = $this->getDoctrine()->getManager();
		$em->remove($news);
		$em->flush();
		
		$this->get('session')->getFlashBag()->add('notice', 'Actualité supprimée');
				
		// redirect to avoid resubmission
		return new RedirectResponse($this->generateUrl('regard_news_list'));
    }
}
